import { createIntl, createIntlCache } from "@formatjs/intl";
import * as RNLocalize from "react-native-localize";
import { I18nManager } from "react-native";
import { get } from "lodash";
const translations = {
  en: require("translations/en.json"),
  zh: require("translations/zh.json"),
} as const;

type Translation = keyof typeof translations;
type TranslationParams = Parameters<(typeof intl)["formatMessage"]>[1];

const fallback = { languageTag: "en", isRTL: false };
const { languageTag, isRTL } =
  RNLocalize.findBestLanguageTag(Object.keys(translations)) ?? fallback;

I18nManager.forceRTL(isRTL);

const intl = createIntl(
  {
    locale: languageTag,
    messages: translations[languageTag as Translation],
  },
  createIntlCache()
);

const translate = (key: string, params?: TranslationParams) => {
  
  // 使用 lodash 的 get 函数来处理嵌套键路径
  const translation = get(intl.messages, key, key);
  return translation as string;
};

export default translate;
